package com.aizuda.boot.modules.third.openApi;

import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.third.openApi.dto.ExchangeRateRequest;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 汇率转换API接口
 *
 * @author yangshen
 * @date 2025-07-25
 */
@RestController
@RequestMapping("/open/exchange-rate")
@Tag(name = "汇率转换API接口")
@Slf4j
public class ExchangeRateApiController {

    @Value("${alicloud.appcode}")
    private String appcode;

    @Value("${alicloud.apis.exchange-rate.host}")
    private String host;

    @Value("${alicloud.apis.exchange-rate.path}")
    private String path;

    private final OkHttpClient httpClient;

    public ExchangeRateApiController() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    @Operation(summary = "汇率转换接口，支持多种货币之间的汇率转换")
    @PostMapping("/convert")
    public SingleResponse<Map<String, Object>> convertExchangeRate(
            @Valid @RequestBody ExchangeRateRequest request) {
        
        try {
            log.info("汇率转换请求，fromCode: {}, toCode: {}, money: {}", 
                    request.getFromCode(), request.getToCode(), request.getMoney());

            // 构建请求体
            FormBody.Builder formBuilder = new FormBody.Builder()
                    .add("fromCode", request.getFromCode())
                    .add("toCode", request.getToCode())
                    .add("money", request.getMoney().toString());

            okhttp3.RequestBody requestBody = formBuilder.build();

            // 构建请求
            Request httpRequest = new Request.Builder()
                    .url(host + path)
                    .addHeader("Authorization", "APPCODE " + appcode)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .post(requestBody)
                    .build();

            // 发送请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    String responseBody = response.body().string();
                    log.info("汇率转换成功，fromCode: {}, toCode: {}, 响应: {}", 
                            request.getFromCode(), request.getToCode(), responseBody);

                    try {
                        // 直接解析为Map对象，保持原始响应结构
                        Map<String, Object> resultMap = JSONObject.parseObject(responseBody, Map.class);
                        return SingleResponse.of(resultMap);
                    } catch (Exception parseException) {
                        log.error("汇率转换响应解析失败，fromCode: {}, toCode: {}, 响应内容: {}, 错误信息: {}",
                                request.getFromCode(), request.getToCode(), responseBody, parseException.getMessage());
                        return SingleResponse.failure(500, "响应数据解析失败");
                    }
                } else {
                    log.error("汇率转换失败，HTTP状态码: {}, fromCode: {}, toCode: {}", 
                            response.code(), request.getFromCode(), request.getToCode());
                    return SingleResponse.failure(500, "汇率转换失败，HTTP状态码: " + response.code());
                }
            }
        } catch (IOException e) {
            log.error("汇率转换网络异常，fromCode: {}, toCode: {}, 错误信息: {}", 
                    request.getFromCode(), request.getToCode(), e.getMessage(), e);
            return SingleResponse.failure(500, "网络请求异常: " + e.getMessage());
        } catch (Exception e) {
            log.error("汇率转换未知异常，fromCode: {}, toCode: {}, 错误信息: {}", 
                    request.getFromCode(), request.getToCode(), e.getMessage(), e);
            return SingleResponse.failure(500, "系统异常: " + e.getMessage());
        }
    }
}
